package main

import (
	"flag"
	"fmt"
	"os"

	"gitee.com/xuender/kits/cmd"
	"gitee.com/xuender/kits/pb"
	"gitee.com/xuender/oils/base"
	"gitee.com/xuender/oils/execs"
	"gitee.com/xuender/oils/logs"
)

func main() {
	flag.CommandLine.Usage = usage
	config := pb.NewConfig("./shell.toml")
	config.Parse()

	if config.Command == "" {
		logs.Panic("缺少执行命令")
	}

	if len(config.Env) > 0 {
		for key, value := range config.Env {
			config.Env[key] = os.Getenv(value)
		}

		for index, key := range config.Args {
			if value, has := config.Env[key]; has {
				config.Args[index] = value
			}
		}
	}

	logs.Info(config)

	out, err := execs.ExecOut(config.Command, config.Args...)
	logs.Error(out)
	base.Panic(err)
}

func usage() {
	fmt.Fprintf(flag.CommandLine.Output(), "kit-shell[%s]\n\n", cmd.ModVersion)
	fmt.Fprintf(flag.CommandLine.Output(), "根据配置执行命令\n\n")
	fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
	flag.PrintDefaults()
	fmt.Fprintf(flag.CommandLine.Output(), "\n模块: %s\n提交: %s\n", cmd.ModPath, cmd.ModSum)
}
